<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部：教师工作台与快捷操作 -->
    <div class="bg-white border-b border-gray-100">
      <div class="container mx-auto px-12 py-8">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-3xl font-bold text-gray-900">教师工作台</h1>
            <p class="text-gray-500 mt-2">专注教学与管理，一站式高效协作</p>
          </div>
          <div class="flex gap-3">
            <el-button @click="goLiveManagement">开启直播</el-button>
            <el-button @click="goStudentClasses">我的班级</el-button>
            <el-button @click="goStudentMembers">学生列表</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 本周课表 -->
    <div class="container mx-auto px-12 py-8">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-2xl font-bold text-gray-900">本周课程安排（课程系列）</h2>
        <div class="flex items-center gap-2">
          <el-button size="small" @click="prevWeek">上周</el-button>
          <el-button size="small" @click="resetToCurrentWeek">本周</el-button>
          <el-button size="small" @click="nextWeek">下周</el-button>
          <span class="text-gray-500 ml-2">{{ weekTitle }}</span>
        </div>
      </div>

      <!-- 周视图网格 -->
      <div class="grid grid-cols-1 md:grid-cols-7 gap-4">
        <div v-for="day in weekDays" :key="day.key" class="bg-white rounded-lg shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
            <div class="font-semibold text-gray-900">{{ day.label }}</div>
            <div class="text-xs text-gray-500">{{ day.dateText }}</div>
          </div>
          <div class="p-3 min-h-[180px]">
            <div v-if="scheduleByDay[day.weekday] && scheduleByDay[day.weekday].length" class="space-y-2">
              <div 
                v-for="item in scheduleByDay[day.weekday]" 
                :key="item.id" 
                class="rounded-lg border border-gray-200 p-3 hover:border-blue-300 hover:shadow-sm transition cursor-pointer"
                @click="openItemActions(item)"
              >
                <div class="flex items-center justify-between gap-2">
                  <div class="min-w-0">
                    <div class="font-medium text-gray-900 truncate">{{ item.seriesName }}</div>
                    <div class="text-sm text-gray-600 mt-1">{{ item.startTime }} - {{ item.endTime }}</div>
                  </div>
                  <div class="flex-shrink-0">
                    <el-button size="small" type="primary" @click.stop="startLive(item)">开播</el-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="text-sm text-gray-400 text-center py-8">暂无课程</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课程操作对话框 -->
    <el-dialog v-model="itemActionVisible" :title="currentItem?.seriesName || '课程操作'" width="420px">
      <div class="space-y-2">
        <div class="text-sm text-gray-600">时间：{{ currentItem?.startTime }} - {{ currentItem?.endTime }}</div>
        <div class="text-xs text-gray-500">班级ID（临时）：{{ currentItem?.fakeClassId }}</div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="itemActionVisible = false">取消</el-button>
          <el-button type="primary" @click="startLive(currentItem)">开播</el-button>
        </span>
      </template>
    </el-dialog>
    
  </div>
  
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 周起始：周一
const getStartOfWeek = (date) => {
  const d = new Date(date)
  const day = d.getDay() || 7 // 周日为0，转为7
  if (day !== 1) {
    d.setHours(0, 0, 0, 0)
    d.setDate(d.getDate() - (day - 1))
  } else {
    d.setHours(0, 0, 0, 0)
  }
  return d
}

const currentWeekStart = ref(getStartOfWeek(new Date()))

const formatDate = (d) => {
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  return `${mm}/${dd}`
}

const weekDays = computed(() => {
  const days = []
  for (let i = 0; i < 7; i++) {
    const d = new Date(currentWeekStart.value)
    d.setDate(d.getDate() + i)
    const weekday = i + 1 // 1-7
    const labelMap = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    days.push({
      key: `${d.toDateString()}`,
      weekday,
      label: labelMap[i],
      dateText: formatDate(d),
      date: d
    })
  }
  return days
})

const weekTitle = computed(() => {
  const start = new Date(currentWeekStart.value)
  const end = new Date(currentWeekStart.value)
  end.setDate(end.getDate() + 6)
  return `${formatDate(start)} - ${formatDate(end)}`
})

const prevWeek = () => {
  const d = new Date(currentWeekStart.value)
  d.setDate(d.getDate() - 7)
  currentWeekStart.value = getStartOfWeek(d)
}

const nextWeek = () => {
  const d = new Date(currentWeekStart.value)
  d.setDate(d.getDate() + 7)
  currentWeekStart.value = getStartOfWeek(d)
}

const resetToCurrentWeek = () => {
  currentWeekStart.value = getStartOfWeek(new Date())
}

// 示例课表数据（以课程系列名称为主，附带临时班级ID）
const schedule = ref([
  { id: 'c-1', weekday: 1, startTime: '09:00', endTime: '10:30', seriesName: 'Java开发系列', fakeClassId: 'cls-1001' },
  { id: 'c-2', weekday: 1, startTime: '14:00', endTime: '15:30', seriesName: '前端工程化系列', fakeClassId: 'cls-1002' },
  { id: 'c-3', weekday: 2, startTime: '10:00', endTime: '11:30', seriesName: 'Java开发系列', fakeClassId: 'cls-1001' },
  { id: 'c-4', weekday: 3, startTime: '08:30', endTime: '10:00', seriesName: '计算机网络系列', fakeClassId: 'cls-1003' },
  { id: 'c-5', weekday: 4, startTime: '13:30', endTime: '15:00', seriesName: '数据库系统系列', fakeClassId: 'cls-1004' },
  { id: 'c-6', weekday: 5, startTime: '09:00', endTime: '11:00', seriesName: '软件工程系列', fakeClassId: 'cls-1005' },
])

const scheduleByDay = computed(() => {
  const map = { 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [] }
  for (const item of schedule.value) {
    if (!map[item.weekday]) map[item.weekday] = []
    map[item.weekday].push(item)
  }
  for (const k of Object.keys(map)) {
    map[k].sort((a, b) => a.startTime.localeCompare(b.startTime))
  }
  return map
})

// 快捷操作
const goLiveManagement = () => { router.push('/LiveManagement') }
const goStudentClasses = () => { router.push('/student-classes') }
const goStudentMembers = () => { router.push('/student-members') }

// 课程操作
const itemActionVisible = ref(false)
const currentItem = ref(null)
const openItemActions = (item) => {
  currentItem.value = item
  itemActionVisible.value = true
}
const startLive = (item) => {
  const clsId = (item && item.fakeClassId) || 'cls-demo'
  // 这里用假的classId拼接到地址或存储备用
  sessionStorage.setItem('currentFakeClassId', clsId)
  router.push('/LiveManagement')
}
</script>

<style scoped>
.min-h\-screen { min-height: 100vh; }
</style>
